package com.forezp.engin.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.forezp.config.datasource.DruidConfiguration;
import com.forezp.config.datasource.DruidProperty;
import com.forezp.service.DataSourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * springboot-jdbc-DataSourceHolder
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/3/16 17:43
 */
@Service
public class DataSourceHolder {

    private Object templateLock = new Object();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private DruidProperty druidProperty;

    @Autowired
    private DataSourceService dataSourceService;

    private Map<Integer, JdbcTemplate> jdbcTemplateMap = new HashMap();


    private JdbcTemplate createJdbcTemplate(com.forezp.entity.DataSource dataSource) throws IOException {

        DataSource dataSource1 = getDataSource(dataSource);
        if (dataSource1 != null)
            return new JdbcTemplate(dataSource1);
        else
            return null;
    }

    private DataSource getDataSource(com.forezp.entity.DataSource dataSource) throws IOException {
        DruidProperty druidProperty1 = new DruidProperty();
        BeanUtils.copyProperties(this.druidProperty, druidProperty1);
        String s = objectMapper.writeValueAsString(druidProperty1);
        DruidProperty druidProperty = objectMapper.readValue(s, DruidProperty.class);
        druidProperty.setUrl(dataSource.getUrl());
        druidProperty.setUsername(dataSource.getName());
        druidProperty.setPassword(dataSource.getPassword());
        DruidDataSource dataSource1 = DruidConfiguration.createDataSource(druidProperty);
        return dataSource1;
    }

    public JdbcTemplate getSuitableJdbcTemplate(Integer dataSourceId) throws IOException {
        JdbcTemplate jdbcTemplate = jdbcTemplateMap.get(dataSourceId);
        if (jdbcTemplate == null) {
            synchronized (templateLock) {
                jdbcTemplate = jdbcTemplateMap.get(dataSourceId);
                if (jdbcTemplate != null) {
                    return jdbcTemplate;
                } else {
                    jdbcTemplate = createJdbcTemplate(dataSourceService.findById(dataSourceId));
                    jdbcTemplateMap.put(dataSourceId, jdbcTemplate);
                    return jdbcTemplate;
                }
            }
        }
        return jdbcTemplate;
    }


}
